package se.recept.kollen.module;

import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.persist.PersistService;
import com.google.inject.persist.jpa.JpaPersistModule;
import com.google.inject.servlet.ServletModule;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

/**
 *
 * @author jocke
 */
public class GuiceSetupContextListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        Injector injector = Guice.createInjector(new ServletModule() {
            @Override
            protected void configureServlets() {
                install(new JpaPersistModule("RKDBPU"));
            }
        });
        sce.getServletContext().setAttribute(Injector.class.getName(), injector);
        injector.getInstance(PersistService.class).start();
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        Injector injector = (Injector) sce.getServletContext().getAttribute(Injector.class.getName());
        if (injector != null) {
            injector.getInstance(PersistService.class).stop();
        }
    }

}
